﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using System.IO;
using KaiXin.DTO.Tycoon;

namespace KaiXin.DAL.XML
{
    public abstract class Persistence<T>
    {

        public abstract string XML_FILE_PATH { get; }

        private FileSystemWatcher _fsw;

        protected XDocument _xd;
        public Persistence()
        {
            if (File.Exists(XML_FILE_PATH))
            {
                _xd = XDocument.Load(XML_FILE_PATH);
            }
            else
            {
                _xd = new XDocument(new XElement("root"));
                _xd.Save(XML_FILE_PATH);
            }
            FileInfo fi = new FileInfo(XML_FILE_PATH);

            _fsw = new FileSystemWatcher(fi.DirectoryName,fi.Name);
            _fsw.NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.Size;
            _fsw.Changed += new FileSystemEventHandler(XML_File_Changed);
            _fsw.EnableRaisingEvents = true;
        }

      
        public virtual void XML_File_Changed(object sender, FileSystemEventArgs e)
        {
            
        }


        protected abstract XElement SearchItem(T item);
        /// <summary>
        /// 添加新的goods
        /// </summary>
        /// <param name="item"></param>
        public abstract void AddItem(T item);
        /// <summary>
        /// 修改原先的item(移除后从新添加)
        /// </summary>
        /// <param name="item"></param>
        public virtual void FixItem(T item)
        {
            XElement el = SearchItem(item);
            if (el!=null)
            {
                el.Remove();
            }
            AddItem(item);
        }
        /// <summary>
        /// 初始化goods的最高与最低价格
        /// </summary>
        /// <param name="item"></param>
        public abstract void InitItem(T item);
        /// <summary>
        /// 删除项目
        /// </summary>
        /// <param name="item"></param>
        public abstract void DeleteItem(T item);
        /// <summary>
        /// 返回所有项目
        /// </summary>
        /// <returns></returns>
        public abstract List<T> GetAllItem();
       
        /// <summary>
        /// 将数据持久化
        /// </summary>
        public void Save()
        {
            _xd.Save(XML_FILE_PATH);
        }
        /// <summary>
        /// 是否存在该实体
        /// </summary>
        /// <param name="item"></param>
        /// <returns></returns>
        public bool IsExist(T item)
        {
            return SearchItem(item) != null;
        }
        
    }
}
